package com.app.micaihu.view.army.activity

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.app.base.BaseMvpActivity
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.bean.news.ShareBean
import com.app.micaihu.configure.Config
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.utils.StatServiceUtils
import com.app.micaihu.view.army.adapter.ArmyHonourListAdapter
import com.app.micaihu.view.army.contract.ArmyDetailContract
import com.app.micaihu.view.army.dialog.ArmyMemberMenuDialog
import com.app.micaihu.view.army.dialog.ArmyMemberShareDialog
import com.app.micaihu.view.army.dialog.ArmySignOutDialog
import com.app.micaihu.view.army.presenter.ArmyDetailPresenter
import com.app.micaihu.view.bean.ArmyDetail
import com.app.micaihu.view.utils.loadCircleImage
import com.app.micaihu.view.utils.loadImage
import com.app.utils.biz.Biz
import com.blankj.utilcode.util.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.umeng.socialize.UMShareAPI
import kotlinx.android.synthetic.main.army_detail_activity.*

/**
 * 军团详情
 */
class ArmyDetailActivity : BaseMvpActivity<ArmyDetailContract.View, ArmyDetailPresenter>(), ArmyDetailContract.View {
    override fun getPresenter() = ArmyDetailPresenter()

    override fun getLayoutId() = R.layout.army_detail_activity

    override fun initBar(initBar: Boolean) {
        super.initBar(false)
        BarUtils.transparentStatusBar(this)
    }

    override fun getBundle(bundle: Bundle) {
        gid = bundle.getString(Config.Extra.id, "")
        toUid = bundle.getString(Config.Extra.toUid, "")
    }

    private var gid = ""
    private var toUid = ""
    private val imageHeight = 300
    private val rgb = 250
    private var userArmyGroupStatus = 0
    private var armyStatus = 0
    private var armyMemberList: List<ArmyDetail.Member>? = null
    private val armySignOutDialog: ArmySignOutDialog by lazy {
        ArmySignOutDialog()
    }
    private val armyMemberMenuDialog: ArmyMemberMenuDialog by lazy {
        ArmyMemberMenuDialog()
    }
    private val armyMemberShareDialog: ArmyMemberShareDialog by lazy {
        ArmyMemberShareDialog()
    }
    private val armyHonourListAdapter: ArmyHonourListAdapter by lazy {
        val armyHonourListAdapter = ArmyHonourListAdapter()
        rvHonour.layoutManager = GridLayoutManager(thisContext, 3)
        armyHonourListAdapter
    }

    override fun setData() {
        if (toUid == Biz.instance.uid()) {
            btnArmy.visibility = View.VISIBLE
        } else {
            btnArmy.visibility = View.GONE
        }

        rvHonour.adapter = armyHonourListAdapter
        mPresenter?.detail(toUid, gid)
        LiveEventBus.get(Config.EventBus.joinArmySuccess, Boolean::class.java).observe(this, Observer {
            LogUtils.e(classTag, "joinArmySuccess->" + it)
            ViewUtils.runOnUiThreadDelayed({
                mPresenter?.detail(toUid, gid)
            }, 100)
        })
        LiveEventBus.get(Config.EventBus.delArmyMemberSuccess, Boolean::class.java).observe(this, Observer {
            LogUtils.e(classTag, "delArmyMemberSuccess->" + it)
            ViewUtils.runOnUiThreadDelayed({ mPresenter?.detail(toUid, gid) }, 100)
        })
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun addListeners() {
        ivBack.setOnClickListener { finish() }
        tvTopRight.setOnClickListener {
            val bundle = Bundle()
            bundle.putBoolean(Config.Extra.showDel, false)
            bundle.putBoolean(Config.Extra.showInviteMicaihu, true)
            armyMemberMenuDialog.arguments = bundle
            armyMemberMenuDialog.show(supportFragmentManager)
        }
        tvAddArmy.setOnClickListener {
            StatServiceUtils.event(Config.EventBauduId.teamapply_button, "军团_申请按钮点击")
            val bundle = Bundle()
            bundle.putString(Config.Extra.id, gid)
            enterPager(ArmyJoinActivity::class.java, bundle)
        }
        btnArmy.setOnClickListener {
            if (armyStatus == 1) {
                when (userArmyGroupStatus) {
                    0 -> {
                        StatServiceUtils.event(Config.EventBauduId.teamapply_button, "军团_申请按钮点击")
                        val bundle = Bundle()
                        bundle.putString(Config.Extra.id, gid)
                        enterPager(ArmyJoinActivity::class.java, bundle)
                    }
                    1 -> {
                        armySignOutDialog.show(supportFragmentManager)
                    }
                    6 -> {
                        ToastUtils.showShort("暂未开放")
                    }
                }
            }
        }
        llMemberRoot.setOnClickListener {
            if (Biz.instance.uid().isEmpty()) {
                UserInforManager.getInstance().toLoginPage(thisActivity)
            } else {
                if (CollectionUtils.size(armyMemberList) > 1) {
                    val bundle = Bundle()
                    bundle.putString(Config.Extra.id, gid)
                    enterPager(ArmyMemberListActivity::class.java, bundle)
                }
            }
        }
        scrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            when {
                scrollY <= 0 -> {
                    rlTitle.setBackgroundColor(Color.argb(0, 0, 0, 0))
                    tvTopTitle.setTextColor(Color.argb(0, rgb, rgb, rgb))
                }
                scrollY in 1..imageHeight -> { //滑动距离小于图的高度时，设置背景和字体颜色颜色透明度渐变
                    val scale: Float = scrollY.toFloat() / imageHeight
                    val alpha = 255 * scale
                    rlTitle.setBackgroundColor(Color.argb(alpha.toInt(), 0, 0, 0))
                    tvTopTitle.setTextColor(Color.argb(alpha.toInt(), rgb, rgb, rgb))
                }
                else -> {
                    rlTitle.setBackgroundColor(Color.argb(255, 0, 0, 0))
                    tvTopTitle.setTextColor(Color.argb(255, rgb, rgb, rgb))
                }
            }
        }
        armySignOutDialog.setOnSignOutClickListener(object : ArmySignOutDialog.OnSignOutClickListener {
            override fun onSignOutClick() {
                mPresenter?.deleteMember(gid, Biz.instance.uid())
            }
        })
        rlLevel.setOnClickListener {
            val bundle = Bundle()
            bundle.putString(Config.Extra.id, gid)
            enterPager(ArmyLevelActivity::class.java, bundle)
        }

        armyMemberMenuDialog.setOnMenuClickListener(object : ArmyMemberMenuDialog.OnMenuClickListener {
            override fun onInvitationClick() {
                armyMemberMenuDialog.dismiss()
                val bundle = Bundle()
                bundle.putString(Config.Extra.id, gid)
                enterPager(ArmyInviteMemberListActivity::class.java, bundle)
            }

            override fun onShareClick() {
                armyMemberMenuDialog.dismiss()
                armyMemberShareDialog.show(supportFragmentManager)
            }

            override fun onDelClick() {
            }
        })
    }

    override fun handleDetail(result: BaseBean<ArmyDetail?>?) {
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
        } else {
            if (result.isSuccess()) {
                result.data?.let { detail ->

                    detail.armyGroupInfo?.let {
                        tvTopTitle.text = it.title
                        tvTopTitle.setTextColor(Color.argb(0, rgb, rgb, rgb))
                        tvTitle.text = it.title
                        ivArmyIcon.loadImage(it.icon)
                        tvGid.text = "番号 " + it.id
                        tvArmyDescription.text = it.description
                        tvMember.text = "共${it.member}人 >"
                        tvWarZone.text = it.war_zone
                        tvGold.text = it.gold
                        tvLevel.text = it.level
                        tvAddTime.text = it.addtime
                        armyHonourListAdapter.setNewInstance(it.honour.toMutableList())

                        /**
                         * 0 待审核  1 已通过   2 加入拒绝 4 创建拒绝
                         */
                        armyStatus = it.status
                        if (armyStatus == 1) {
                            /**
                             * 客户端展示判断，0绿色申请加入按钮，1您已加入军团，2您已申请其他军团，3您已加入其他军团， 4已申请，等待通过，5已拒绝
                             */
                            userArmyGroupStatus = detail.userArmyGroupStatus
                            when (userArmyGroupStatus) {
                                0 -> {
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.app_theme))
                                    btnArmy.text = "申请加入"
                                }
                                1 -> {
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.app_theme))
                                    btnArmy.text = "退出军团"
                                }
                                2 -> {
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.colorC1C1C1))
                                    btnArmy.text = "您已申请其他军团"
                                }
                                3 -> {
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.colorC1C1C1))
                                    btnArmy.text = "您已加入其他军团"
                                }
                                4 -> {
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.colorC1C1C1))
                                    btnArmy.text = "已申请，等待通过"
                                }
                                5 -> {
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.colorC1C1C1))
                                    btnArmy.text = "已拒绝"
                                }
                                6 -> {
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.colorC1C1C1))
                                    btnArmy.text = "转让军团"
                                }
                            }
                            if (toUid == Biz.instance.uid()) {
                                if (userArmyGroupStatus == 0) {
                                    tvAddArmy.visibility = View.VISIBLE
                                } else {
                                    tvAddArmy.visibility = View.GONE
                                }
                            }

                            if (userArmyGroupStatus == 6) {
                                tvTopRight.visibility = View.VISIBLE
                                mPresenter?.share()
                            } else {
                                tvTopRight.visibility = View.GONE
                            }
                        } else {
                            when (armyStatus) {
                                0 -> {
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.colorC1C1C1))
                                    btnArmy.text = "等待审核"
                                }
                                2 -> {
                                    //加入拒绝
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.colorC1C1C1))
                                    btnArmy.text = "已拒绝"
                                }
                                4 -> {
                                    //创建拒绝
                                    cardViewArmy.setCardBackgroundColor(ColorUtils.getColor(R.color.colorC1C1C1))
                                    btnArmy.text = "已拒绝"
                                }
                                else -> {

                                }
                            }
                        }

                    }
                    detail.memberList?.let {
                        armyMemberList = it
                        llMember.removeAllViews()
                        for ((index, member) in it.withIndex()) {
                            if (index >= 4) break
                            val item = ImageView(thisContext)
                            val params = LinearLayout.LayoutParams(SizeUtils.dp2px(40f), SizeUtils.dp2px(40f))
//                            if (index > 0) {
//                                params.leftMargin = -SizeUtils.dp2px(10f)
//                            } else {
//                                params.leftMargin = 0
//                            }
                            item.loadCircleImage(member.avatar, R.drawable.user_head_def)
                            item.layoutParams = params
                            llMember.addView(item)
                        }
                    }

                }
            } else {
                ToastUtils.showShort(result.msg)
            }

        }
    }

    override fun handleDeleteMember(result: BaseBean<Any?>?) {
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
        } else {
            if (result.isSuccess()) {
                LiveEventBus.get(Config.EventBus.signOutArmySuccess).post(true)
                finish()
            }
            ToastUtils.showShort(result.msg)
        }
    }

    override fun handleShare(result: BaseBean<ShareBean?>?) {
        if (result != null) {
            if (result.isSuccess()) {
                result.data?.let {
                    val bundle = Bundle()
                    bundle.putSerializable(Config.Extra.share, it)
                    armyMemberShareDialog.arguments = bundle
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

}